import Valid from './valid'
const { $fn } = window

// 验证密码确认输入
const confirm_pwd = ({ getFieldValue }) => ({
	validator : (_, value) => !value || getFieldValue('password') === value ? Promise.resolve() : Promise.reject('两次密码输入不一致')
})

const rules = (v, message) => {
	if(!$fn.isObject(v)) return null
	let {  r, rule, name, label, type, mul, valid } = v
	let required = r ? { required: !v.disabled && r, message  } : null
	let _rules = {}
	
	if( name && name.includes('confirm_pwd') ) {
		let dependencies = $fn.isArray(v.dep) ? v.dep : ( v.dep ? [ v.dep ] : [] )
		_rules = {
			dependencies :  v.dep ? dependencies : ['password'],
			rule :  r ? [ required, confirm_pwd ] : [confirm_pwd ]
		}
		return _rules
	}
	if( valid !== false && valid !== 0 ){
		rule =  getValidStr( rule, name )
	}
	
	if( $fn.isString(rule) ){ // rule:'phone'
		_rules = Valid?.[rule]?.(label)
	}else if( $fn.isObject(rule) ) { // rule:{ a:1 }
		for(let i in rule){
			let value = rule[i]
			_rules = Valid[i](label, value )
		}
	}else{
		// 自动验证
		if( v.range && $fn.hasArray(v.range) ){
			_rules = Valid?.['range']?.(label, v.range)
		}else{
			if( $fn.isNumber(v.max) ) _rules = Valid?.['max']?.(label, v.max)
			if(type === 'number' && $fn.isEmpty(v.max)){
				if( $fn.isNumber(v.min) ) {
					_rules = Valid?.['min']?.(label, v.min)
				}else{
					_rules = Valid?.['min']?.(label, 0)
				}
			}
			if( $fn.isNumber(v.maxLen) ) {
				_rules = Valid?.['maxLen']?.(label, v.maxLen, mul)
			}else{
				if( type==='textarea' && !v.maxLength && v.maxLength !== null ) _rules = Valid?.['maxLen']?.(label, 30, mul)
			}
			
			if( $fn.isNumber(v.minLen) ) _rules = Valid?.['minLen']?.(label, v.minLen, mul)
			if( $fn.isNumber(v.len) ) _rules = Valid?.['len']?.(label, v.len)
			
			if( v.money) _rules = Valid?.['money']?.(label, v.money)
		}
	}
	if( $fn.hasObject( _rules ) ){
		return { rule: r ? [ required, _rules ] : [ _rules ] }
	}else{
		return { rule: r ? [ required ] : [] }
	}
}
//
const getValidStr = (rule, name) => {
    if(!rule && rule !== 0 && rule !== false && name){
        if( name.includes('phone') ) rule = 'phone'
        if( name.includes('email') ) rule = 'email'
		if( name === 'age' ) rule = 'age'
        if( name.includes('password') ) rule = 'password'
        if( name.includes('idcard') ) rule = 'idcard'
        if( name.includes('bank_card') ) rule = 'bank_card'
    }
    return rule
}

export default rules